package net.jiastudy.web.rest.controller.sys;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.jiastudy.biz.sys.entity.File;
import net.jiastudy.biz.sys.entity.FileTarget;
import net.jiastudy.biz.sys.service.AttachmentService;
import net.jiastudy.biz.sys.service.FileService;
import net.jiastudy.core.base.BaseController;
import net.jiastudy.core.exception.ServiceException;
import net.jiastudy.core.utils.UploadUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/files")
@Api(value = "FileController  文件上传下载")
public class FileController extends BaseController {

    @Value("${upload.path.base}")
    private String basePath;
    @Value("${upload.path.public}")
    private String publicUploadPath;
    @Resource
    private FileService fileService;
    @Resource
    private AttachmentService attachmentService;

    @RequestMapping(path = "/{target}", method = RequestMethod.POST)
    @ApiOperation(value = "文件上传", notes = "这里上传的是不能直接访问")
    public File upload(@PathVariable FileTarget target, @RequestParam("file") MultipartFile file) {
        if (file.isEmpty() || file.getSize() == 0) {
            return null;
        }
        String fileName = file.getOriginalFilename();
        String suffixName = UploadUtil.getSuffixName(fileName);
        Date now = new Date();
        String filePath = UploadUtil.UPLOAD_PATH + UploadUtil.makeFileDir(now);
        String newFileName = UploadUtil.makeRandomFileName(now, suffixName);
        newFileName = "/" + newFileName;
        boolean bool = UploadUtil.mkdirs(basePath + filePath);
        if (!bool) {
            logger.error("创建目录失败，请检查权限");
            new ServiceException("500", "创建目录失败，请检查权限");
        }
        java.io.File dest = new java.io.File(basePath + filePath + newFileName);
        try {
            file.transferTo(dest);
        } catch (IllegalStateException | IOException e) {
            logger.error("文件上传出错了：", e);
        }
        File fileEntiny = new File();
        fileEntiny.setExtName(suffixName);
        fileEntiny.setName(fileName);
        fileEntiny.setPath(filePath + newFileName);
        fileEntiny.setSize(file.getSize());
        fileEntiny.setTarget(target);
        return fileService.create(fileEntiny);
    }

    @RequestMapping(path = "/public/{target}", method = RequestMethod.POST)
    @ApiOperation(value = "文件上传", notes = "这里上传的是可以直接访问")
    public File uploadPublic(@PathVariable FileTarget target, @RequestParam("file") MultipartFile file) {
        if (file.isEmpty() || file.getSize() == 0) {
            return null;
        }
        String fileName = file.getOriginalFilename();
        String suffixName = UploadUtil.getSuffixName(fileName);
        Date now = new Date();
        String filePath = UploadUtil.PUBLIC_PATH + UploadUtil.makeFileDir(now);
        String newFileName = UploadUtil.makeRandomFileName(now, suffixName);
        newFileName = "/" + newFileName;
        boolean bool = UploadUtil.mkdirs(publicUploadPath + filePath);
        if (!bool) {
            logger.error("创建目录失败，请检查权限");
            new ServiceException("500", "创建目录失败，请检查权限");
        }
        java.io.File dest = new java.io.File(publicUploadPath + filePath + newFileName);
        try {
            file.transferTo(dest);
        } catch (IllegalStateException | IOException e) {
            logger.error("文件上传出错了：", e);
        }
        File fileEntiny = new File();
        fileEntiny.setExtName(suffixName);
        fileEntiny.setName(fileName);
        fileEntiny.setPath(filePath + newFileName);
        fileEntiny.setSize(file.getSize());
        fileEntiny.setTarget(target);
        return fileService.create(fileEntiny);
    }

    @RequestMapping(path = "/{id}/download", method = RequestMethod.GET)
    @ApiOperation(value = "文件下载")
    public void download(@PathVariable Long id, HttpServletResponse response) {
        File fileEntiny = fileService.get(id);
        Path file = Paths.get(basePath, fileEntiny.getPath());
        if (Files.exists(file)) {
            try {
                UploadUtil.setFileDownloadHeader(response, fileEntiny.getName());
                Files.copy(file, response.getOutputStream());
            } catch (IOException e) {
                logger.error("下载出错：", e);
            }
        }
    }

    @RequestMapping(path = "/{id}/img", method = RequestMethod.GET)
    @ApiOperation(value = "文件直接查看")
    public void show(@PathVariable Long id, HttpServletResponse response) {
        File fileEntiny = fileService.get(id);
        Path file = Paths.get(basePath, fileEntiny.getPath());
        if (Files.exists(file)) {
            response.setContentType("image/*");
            try {
                Files.copy(file, response.getOutputStream());
            } catch (IOException e) {
                logger.error("显示文件出错：", e);
            }
        }
    }

    @RequestMapping(path = "/attachment/{attachmentId}", method = RequestMethod.GET)
    @ApiOperation(value = "文件夹的文件列表")
    public List<File> show(@PathVariable Long attachmentId) {
        return attachmentService.findFildsByAttachmentId(attachmentId);
    }

    @RequestMapping(path = "/{id}/preview", method = RequestMethod.GET)
    @ApiOperation(value = "文件预览")
    public void preview(@PathVariable Long id, HttpServletRequest request, HttpServletResponse response) throws IOException {
        StringBuffer host;
        StringBuffer url = request.getRequestURL();
        String uri = request.getRequestURI();

        host = url.replace(url.indexOf(uri), url.length(), "");
        String previewUrl = fileService.getFilePreviewPath(id, host);

        previewUrl = previewUrl.substring(2, previewUrl.length() - 2);
        response.sendRedirect(previewUrl);
    }
}
